package com.hello.system.controller.wx;

import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestHeader;
import com.hello.common.core.web.controller.BaseController;
import com.hello.common.core.web.domain.AjaxResult;
import com.hello.common.core.web.page.TableDataInfo;
import com.hello.common.security.utils.SecurityUtils;
import com.hello.system.annotation.ContentSecurity;
import com.hello.system.domain.TreeHoleEntries;
import com.hello.system.domain.TreeHoleReadRecords;
import com.hello.system.domain.TreeHoleReports;
import com.hello.system.service.ITreeHoleEntriesService;
import com.hello.system.service.ITreeHoleReadRecordsService;
import com.hello.system.service.ITreeHoleReportsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.github.pagehelper.PageInfo;

/**
 * 微信小程序树洞内容Controller
 * 
 * @author hello
 * @date 2025-05-30
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/wx/api/treehole")
public class WxMiniappTreeHoleController extends BaseController {
    private final ITreeHoleEntriesService treeHoleEntriesService;
    private final ITreeHoleReadRecordsService treeHoleReadRecordsService;
    private final ITreeHoleReportsService treeHoleReportsService;
    
    /**
     * 小程序查询树洞内容列表，包含已阅状态
     */
    @GetMapping("/list")
    public AjaxResult listWithReadStatus(TreeHoleEntries treeHoleEntries) {
        startPage();
        List<TreeHoleEntries> list = treeHoleEntriesService.selectTreeHoleEntriesList(treeHoleEntries);
        // 保存分页信息
        PageInfo<TreeHoleEntries> pageInfo = new PageInfo<>(list);
        
        // 获取当前用户ID
        Long userId = SecurityUtils.getUserId();
        
        // 创建过滤后的列表
        List<TreeHoleEntries> filteredList = new java.util.ArrayList<>();
        
        // 为每个树洞内容添加已阅状态并过滤举报超过10次的内容
        for (TreeHoleEntries entry : list) {
            // 查询当前树洞的举报次数
            int reportCount = treeHoleReportsService.countReportsByTreeHoleId(entry.getEntryId());
            
            // 如果举报次数超过10次，则不显示该内容
            if (reportCount >= 10) {
                continue;
            }
            
            // 查询当前用户是否已阅读该条目
            boolean hasRead = treeHoleReadRecordsService.checkUserHasRead(userId, entry.getEntryId());
            
            // 动态添加已阅字段
            entry.getParams().put("hasRead", hasRead);
            
            // 添加到过滤后的列表
            filteredList.add(entry);
        }
        
        // 微信小程序返回格式
        return AjaxResult.success("操作成功", new java.util.HashMap<String, Object>() {{
            put("list", filteredList);
            put("total", pageInfo.getTotal());
            put("pageNum", pageInfo.getPageNum());
            put("pageSize", pageInfo.getPageSize());
        }});
    }
    
    /**
     * 小程序创建树洞内容
     */
    @PostMapping
    @ContentSecurity(fieldName = "content")
    public AjaxResult createEntry(@RequestBody TreeHoleEntries treeHoleEntries, @RequestHeader(value = "X-WX-OPENID", required = false) String openid) {
        // 内容安全检测由@ContentSecurity注解处理，通过请求头获取openid
        
        log.info("小程序发布树洞内容，openid: {}", openid);
        
        // 设置当前用户ID
        treeHoleEntries.setUserId(SecurityUtils.getUserId());
        
        // 插入数据
        int rows = treeHoleEntriesService.insertTreeHoleEntries(treeHoleEntries);
        if (rows > 0) {
            // 获取完整的树洞对象（包含ID等信息）
            TreeHoleEntries newEntry = treeHoleEntriesService.selectTreeHoleEntriesByEntryId(treeHoleEntries.getEntryId());
            AjaxResult result = AjaxResult.success("发布成功");
            result.put("data", newEntry);
            return result;
        }
        
        return error("发布失败");
    }
    
    /**
     * 小程序获取树洞内容详情，包含已阅状态，并标记为已阅
     */
    @GetMapping("/{entryId}")
    public AjaxResult getInfoWithReadStatus(@PathVariable("entryId") Long entryId) {
        // 获取树洞内容
        TreeHoleEntries entry = treeHoleEntriesService.selectTreeHoleEntriesByEntryId(entryId);
        if (entry != null) {
            // 查询当前树洞的举报次数
            int reportCount = treeHoleReportsService.countReportsByTreeHoleId(entryId);
            
            // 如果举报次数超过10次，则不显示该内容
            if (reportCount >= 10) {
                return error("该内容因多次举报已被屏蔽");
            }
            
            // 获取当前用户ID
            Long userId = SecurityUtils.getUserId();
            
            // 查询是否已阅
            boolean hasRead = treeHoleReadRecordsService.checkUserHasRead(userId, entryId);
            entry.getParams().put("hasRead", hasRead);
            
            // 如果未阅读，则添加已阅记录
            if (!hasRead) {
                TreeHoleReadRecords readRecord = new TreeHoleReadRecords();
                readRecord.setUserId(userId);
                readRecord.setEntryId(entryId);
                treeHoleReadRecordsService.insertTreeHoleReadRecords(readRecord);
                
                // 更新状态
                entry.getParams().put("hasRead", true);
                
                // 增加查看次数
                treeHoleEntriesService.incrementViewsCount(entryId);
            }
        }
        
        return success(entry);
    }
    
    /**
     * 标记树洞内容为已读
     */
    @PostMapping("/read/{entryId}")
    public AjaxResult markAsRead(@PathVariable("entryId") Long entryId) {
        // 先检查树洞条目是否存在
        TreeHoleEntries entry = treeHoleEntriesService.selectTreeHoleEntriesByEntryId(entryId);
        if (entry == null) {
            return error("树洞内容不存在");
        }
        
        Long userId = SecurityUtils.getUserId();
        
        // 检查是否已阅
        if (treeHoleReadRecordsService.checkUserHasRead(userId, entryId)) {
            return success("内容已阅");
        }
        
        // 添加已阅记录
        TreeHoleReadRecords readRecord = new TreeHoleReadRecords();
        readRecord.setUserId(userId);
        readRecord.setEntryId(entryId);
        int rows = treeHoleReadRecordsService.insertTreeHoleReadRecords(readRecord);
        
        // 增加查看次数
        if (rows > 0) {
            treeHoleEntriesService.incrementViewsCount(entryId);
        }
        
        return rows > 0 ? success("标记为已读成功") : error("标记为已读失败");
    }
    
    /**
     * 取消树洞内容已读标记
     */
    @PostMapping("/unread/{entryId}")
    public AjaxResult cancelRead(@PathVariable("entryId") Long entryId) {
        // 先检查树洞条目是否存在
        TreeHoleEntries entry = treeHoleEntriesService.selectTreeHoleEntriesByEntryId(entryId);
        if (entry == null) {
            return error("树洞内容不存在");
        }
        
        Long userId = SecurityUtils.getUserId();
        
        // 检查是否已阅
        if (!treeHoleReadRecordsService.checkUserHasRead(userId, entryId)) {
            return success("内容未阅");
        }
        
        // 删除已阅记录
        int rows = treeHoleReadRecordsService.deleteTreeHoleReadRecordsByUserIdAndEntryId(userId, entryId);
        
        return rows > 0 ? success("取消已读标记成功") : error("取消已读标记失败");
    }

    /**
     * 小程序提交树洞举报
     */
    @PostMapping("/report")
    @ContentSecurity(fieldName = "reportReason")
    public AjaxResult reportTreeHole(@RequestBody TreeHoleReports treeHoleReports, @RequestHeader(value = "X-WX-OPENID", required = false) String openid) {
        try {
            // 内容安全检测由@ContentSecurity注解处理，通过请求头获取openid
            log.info("小程序举报树洞内容，openid: {}", openid);
            
            // 检查必填参数
            if (treeHoleReports.getTreeHoleId() == null) {
                return error("树洞ID不能为空");
            }
            
            // 设置举报者ID为当前登录用户
            treeHoleReports.setReporterUserId(SecurityUtils.getUserId());
            
            // 验证树洞是否存在
            TreeHoleEntries entry = treeHoleEntriesService.selectTreeHoleEntriesByEntryId(treeHoleReports.getTreeHoleId());
            if (entry == null)
            {
                return error("树洞内容不存在");
            }
            
            // 执行插入操作
            return toAjax(treeHoleReportsService.insertTreeHoleReports(treeHoleReports));
        } catch (Exception e) {
            log.error("举报树洞失败", e);
            return error("举报失败：" + e.getMessage());
        }
    }
} 